<?php

/**
 * databases actions.
 *
 * @package    ecrm
 * @subpackage databases
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class databasesActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->tableColumns = DatabaseSourceTable::TableColumns();
  }

	public function executeAjaxdata(sfWebRequest $request) 
	{
		sfConfig::set('sf_web_debug', false);
		$this->getResponse()->setContentType('application/json');
		$this->databases = Doctrine::getTable('DatabaseSource');
		$json = $this->databases->fetchData($request);
		return $this->renderText($json);
	}

  public function executeAjaxNewForm(sfWebRequest $request) {
    sfConfig::set('sf_web_debug', false);
    $form = new DatabaseSourceForm();
    return $this->renderPartial("databaseForm", array("form"=>$form));
  }

	public function executeAjaxEditForm(sfWebRequest $request) {
		$data = Doctrine_Core::getTable('DatabaseSource')->findOneById($request->getParameter('id'));
		$form = new DatabaseSourceForm($data);
    $conn = Doctrine_Manager::connection($data->getDriver().'://'.$data->getUsername().':'.$data->getPassword().'@'.$data->getServer().'/'.$data->getName(), 'connection 1');
    if($data->getCustomSql() == '' || is_null($data->getCustomSql())) {
    	$sqlQuery = 'SELECT * FROM `'.$data->getTableSource().'`';
    }
    else {
    	$sqlQuery = $data->getCustomSql();
    }
    $sqlQuery.=' LIMIT 1';
    $tableResult = $conn->execute($sqlQuery)->fetchObject();
	  $tableFields = array_keys((array)$tableResult);
    
//     var_dump($tableFields);
//     exit();

        //get field mapping
        $manager = Doctrine_Manager::getInstance();
        $manager->setCurrentConnection('doctrine');
        $fieldsMap = null;
		$fieldMappings = Doctrine_Core::getTable('FieldMapping')->getFieldMapping($request->getParameter('id'));
        
		return $this->renderPartial("databaseForm", array("form" => $form,'tableFields'=>$tableFields, 'fieldsMaps' => $fieldMappings));
	}

  public function executeAjaxSave(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    sfConfig::set('sf_web_debug', false);
    $this->getResponse()->setContentType('application/json');
    $this->form = new DatabaseSourceForm();
    $data_array = $this->processForm($request, $this->form);
    return $this->renderText(json_encode($data_array));
  }

  private function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()));

    $boolIsNew = ($form->getObject()->isNew() ? true : false );

    if ($form->isValid()) {
      unset($form['_csrf_token']);
      try {
        $application = $form->save();

        $data_arr = array("valid" => 'true', "message" => 'Data successfully saved!', "id" => $application->getId());
      }
      catch (Exception $exc) {
        $data_arr = array("valid" => 'false', "message" => $exc->getMessage());
      }
    }
    else {
      $errors = $form->getErrorSchema()->getErrors();
      $errorText = '';
      foreach($errors as $key=>$val) {
        $errorText .= $key.': '.$val.'|';
      }
      $data_arr = array("valid" => 'false', "message" => $errorText);
    }
    return $data_arr;
  }

  public function executeUpdate(sfWebRequest $request) {
      $this->forward404unless($request->isXmlHttpRequest());
      $formValues = $request->getParameter('database_source');
      $this->forward404Unless($application = Doctrine_Core::getTable('DatabaseSource')->find(array($formValues['id']))  , sprintf('Object DatabaseSource does not exist (%s).', array($formValues['id'])));
      $this->getResponse()->setContentType('application/json');
      $this->form = new DatabaseSourceForm($application);
      $data_array = $this->processForm($request, $this->form);

      foreach($request->getParameter('db_fields') as $key=>$field) {
        $existingField = Doctrine_Core::getTable('FieldMapping')->findOneByDatabaseSourceIdAndExternalFieldName($this->form->getObject()->getId(),$key);
        if(!$existingField && $field != '') {
//          var_dump($key.'-'.$field);
          $newField = new FieldMapping();
          $newField->setDatabaseSourceId($this->form->getObject()->getId());
          $newField->setExternalFieldName($key);
          $newField->setInternalFieldName($field);
          $newField->save();
        }else{
            $existingField->setInternalFieldName($field);
            $existingField->save();
        }
      }
      
      return $this->renderText(json_encode($data_array));
  }

  public function executeDelete(sfWebRequest $request) {
      $this->forward404unless($request->isXmlHttpRequest());
      sfConfig::set('sf_web_debug', false);
      $this->getResponse()->setContentType('application/json');
      $this->forward404Unless($application = Doctrine_Core::getTable('DatabaseSource')->find(array($request->getParameter('id'))), sprintf('Object DatabaseSource does not exist (%s).', $request->getParameter('id')));
      try {
        $application->delete();
        $data_arr = array("valid" => 'true', "message" => 'Data was successfully deleted!');
      }
      catch (Exception $exc) {
        $data_arr = array("valid" => 'false', "message" => $exc->getMessage());
      }
      return $this->renderText(json_encode($data_arr));
  }


}
